<template>
  <div class="course-detail-container">
    <Breadcrumb @Back="toAssign">
      <template #bread-name>
        {{ taskInfo.name }}
      </template>
      <template #more-info>
        <div class="class-box">
          <label
            class="class-label"
            v-for="item in taskInfo.classList.slice(0, 3)"
            :key="item.value"
            :class="{ active: item.value === classSelect.value }"
            @click="classSelect = item"
            >{{ (item.grade_name || '') + item.label }}</label
          >
          <el-dropdown
            v-if="taskInfo.classList.length > 3"
            popper-class="course-select"
          >
            <label
              class="more-class class-label"
              :class="{
                active: taskInfo.classList
                  .slice(3)
                  .find(i => i.value === classSelect.value)
              }"
              v-if="taskInfo.classList.length > 3"
              >更多<img src="@/assets/images/assignment/down-icon.png"
            /></label>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  v-for="item in taskInfo.classList.slice(3)"
                  @click="classSelect = item"
                  :class="{ active: item.value === classSelect.value }"
                  :key="item.value"
                  >{{ item.label }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </template>
    </Breadcrumb>
    <main class="content">
      <el-tabs
        v-model="activeName"
        class="course-tab"
        @tab-change="onTabChange"
      >
        <template #add-icon> 23213 </template>
        <el-tab-pane
          :label="tab.text"
          :name="tab.value"
          v-for="(tab, index) in tabList"
          :key="index"
          :disabled="
            (tab.value === 4 && retrainStatus?.retrain_task === 0) ||
            (tab.value === 3 && taskInfo.classList.length <= 1) ||
            (tab.value === 6 &&
              !oneThreeInfo.questionList.length &&
              !relationList.length)
          "
        >
          <component
            v-if="activeName === tab.value"
            :is="tab.cpn"
            :task-info="taskInfo"
            :class-select="classSelect"
            :taskId="taskInfo.taskId"
            :activeName="activeName"
            :retrainStatus="retrainStatus"
            :questionList="oneThreeInfo.questionList"
            :studentList="oneThreeInfo.studentList"
            @getOneThreeInfo="getOneThreeInfo"
          />
        </el-tab-pane>
      </el-tabs>
      <div class="action-btn flex">
        <div
          @click="dialogVisible = true"
          class="setting-btn hover"
          v-if="retrainStatus?.retrain !== 1 && taskInfo.taskType !== 3"
        >
          <el-icon class="setting-icon">
            <Setting />
          </el-icon>
          重练设置
        </div>
        <div
          @click="toCourse"
          class="course-btn hover"
          v-if="taskInfo.taskType == 1"
        >
          查看课程内容
        </div>
        <div
          class="course-btn hover"
          @click="onDownLoadFile"
          v-if="taskInfo.fileList.length"
        >
          下载任务附件
        </div>
        <el-button round type="primary" @click="onPushClass"
          >催交作业</el-button
        >
      </div>
    </main>
    <RetrainDialog
      :taskInfo="taskInfo"
      :visible="dialogVisible"
      @close="dialogVisible = false"
    ></RetrainDialog>
  </div>
</template>

<script setup>
import { ref, shallowRef } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Setting } from '@element-plus/icons-vue'
import {
  getTaskUrge,
  getIsRetrain,
  getTaskInfoById,
  getRelationTask
} from '@/apis/assignment'
import { useAuthStore } from '@/stores/auth-store.js'
import Breadcrumb from '@/components/Breadcrumb.vue'
import CourseTable1 from '../components/Finish.vue'
import PracticeTab1 from '../components/FinishPractice.vue'
import CourseTable2 from '../components/Score.vue'
import CourseTable3 from '../components/Compare.vue'
import RetrainDialog from '../components/RetrainDialog.vue'
import TaskDetail from '../components/Task.vue'
import OneThreePreview from '../one-three/OneThreePreview.vue'
import OneThreeTask from '../one-three/OneThreeTask.vue'
import router from '@/router'
import axios from 'axios'

const authStore = useAuthStore()
const route = useRoute()
const tabList = ref([
  {
    value: 5,
    text: '完成情况',
    cpn: shallowRef(PracticeTab1)
  },
  {
    value: 0,
    text: '课程目录',
    cpn: shallowRef(CourseTable1)
  },
  {
    value: 1,
    text: '成绩详情',
    cpn: shallowRef(CourseTable2)
  },
  {
    value: 2,
    text: '任务详情',
    cpn: shallowRef(TaskDetail)
  },
  {
    value: 3,
    text: '对比分析',
    cpn: shallowRef(CourseTable3)
  },
  {
    value: 4,
    text: '错题重练',
    cpn: shallowRef(CourseTable2)
  },
  {
    value: 6,
    text: '举一反三',
    cpn: null
  }
])
const classSelect = ref()
const activeName = ref(0)
const taskInfo = ref({
  classList: [],
  taskId: '',
  fileList: [],
  courseId: 0,
  taskType: 0, // 1-课程 2-习题
  name: ''
})

// 错题重练
const dialogVisible = ref(false)
const onDownLoadFile = () => {
  taskInfo.value.fileList.forEach(async (file, index) => {
    const response = await axios.get(file.url, {
      responseType: 'blob' // 将响应类型设置为 blob
    })

    const blob = new Blob([response.data])
    const downloadUrl = URL.createObjectURL(blob)

    const a = document.createElement('a')
    a.href = downloadUrl
    a.download = file.name || 'downloaded_file'
    document.body.appendChild(a)
    a.click() // 模拟点击以触发下载
    document.body.removeChild(a) // 移除元素

    // 清理对象 URL
    URL.revokeObjectURL(downloadUrl)
  })
}

const onPushClass = async () => {
  const res = await getTaskUrge({
    task_id: taskInfo.value.taskId
  })
  if (res.code === 1) {
    ElMessage.success('催交成功！')
  }
}

const toCourse = () => {
  router.push({
    path: `/question-bank/lesson/preview/${taskInfo.value.courseId}`
  })
}

const retrainStatus = ref()
const getRetrainStatus = async () => {
  const res = await getIsRetrain({
    task_id: route.query?.taskId,
    teacher_id: authStore.userInfo.userId
  })
  retrainStatus.value = res?.data || {}
}

const getTaskData = async () => {
  const res = await getTaskInfoById({
    task_id: route.query?.taskId
  })
  const temp = res?.data || {}
  taskInfo.value = {
    classList: (temp.class_info || []).map(item => ({
      value: item.id,
      label: item.name,
      ...item
    })),
    taskId: temp.task_id,
    fileList: temp.annex || [],
    courseId: temp.course_id,
    taskType: temp.task_type,
    name: temp.task_name,
    ...temp
  }
  classSelect.value = taskInfo.value.classList[0]
  if (taskInfo.value.taskType == 2 || taskInfo.value.taskType == 3) {
    tabList.value = tabList.value.splice(1)

    tabList.value[0].cpn = PracticeTab1
    tabList.value[0].text = '完成情况'
  } else if (taskInfo.value.taskType == 1) {
    activeName.value = 5
  }
}

// 举一反三相关
const onTabChange = () => {
  if (oneThreeInfo.value.questionList.length) {
    oneThreeInfo.value = {
      questionList: [],
      studentList: []
    }
    getRelationTaskInfo()
  }
}
const relationList = ref([]) // 举一反三任务列表
const oneThreeInfo = ref({
  questionList: [],
  studentList: []
})
const getRelationTaskInfo = async () => {
  const res = await getRelationTask({
    relation_task_id: taskInfo.value.taskId
  })
  relationList.value = res.data || []
  let tab = tabList.value.find(item => item.value === 6)
  tab.cpn = shallowRef(OneThreeTask)
}
const toAssign = () => {
  router.push({
    name: 'assignment'
  })
}
const getOneThreeInfo = param => {
  oneThreeInfo.value = param
  activeName.value = 6
  let tab = tabList.value.find(item => item.value === 6)
  tab.cpn = shallowRef(OneThreePreview)
}

const initData = async () => {
  await getTaskData()
  getRelationTaskInfo()
  getRetrainStatus()
}

initData()
</script>

<style lang="less" scoped>
.course-detail-container {
  .content {
    position: relative;
    margin-top: 20px;

    .course-tab {
      /* stylelint-disable-next-line */
      :deep(.el-tabs__nav-wrap:after) {
        background-color: unset;
      }
    }

    .action-btn {
      position: absolute;
      right: 20px;
      top: 0px;
      gap: 20px;

      :deep(.el-button) {
        font-size: 14px;

        --el-color-primary-light-3: #5466e7;
      }

      .class-select {
        width: 200px;
      }

      .setting-btn {
        display: inline-flex;
        align-items: center;
        gap: 4px;
        color: #5466e7;

        .setting-icon {
          font-size: 20px;
        }
      }

      .course-btn {
        color: #5466e7;
        border-bottom: 1px solid #5466e7;
      }
    }
  }

  .class-box {
    .class-label {
      display: inline-block;
      line-height: 32px;
      height: 32px;
      padding: 0 12px;
      background-color: #fff;
      font-size: 14px;
      margin-right: 12px;
      cursor: pointer;
      color: #333333;

      &:hover {
        background-color: #e0e4ff;
      }

      &.active {
        color: #5466e7;
        background-color: #d7e1ff;
      }

      &.more-class {
        &:focus-visible {
          outline: unset;
        }
        img {
          margin-left: 8px;
          width: 12px;
        }
      }
    }
  }
}
</style>

<!-- eslint-disable -->
<style lang="less">
.course-select {
  /* stylelint-disable ebag/selector-class-pattern */
  .el-dropdown-menu__item {
    font-size: 14px;

    &.active {
      color: #5466e7;
      background-color: #d7e1ff;
    }

    &:hover {
      background-color: #e0e4ff;
    }
  }
}
</style>
